package io.cici.cc.mybatis.lite.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;


public class ExceptionUtil {


    /**
     * InvocationTargetException是在使用反射中发生的异常，包裹了原始的异常
     * UndeclaredThrowableException是在代理中发生的异常，包裹了原始的异常
     * 拆解InvocationTargetException和UndeclaredThrowableException异常的包装，从而得到被包装的真正异常
     *
     * @param wrapped 包装后的异常
     * @return 拆解出的被包装异常
     */
    public static Throwable unwrapThrowable(Throwable wrapped) {
        // 该变量用以存放拆包得到的异常
        Throwable unwrapped = wrapped;
        while (true) {
            if (unwrapped instanceof InvocationTargetException) {
                // 拆包获得内部异常
                unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
            } else if (unwrapped instanceof UndeclaredThrowableException) {
                // 拆包获得内部异常
                unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
            } else {
                // 该异常无需拆包
                return unwrapped;
            }
        }
    }

}